package com.jshoperxms.controller.mall.backstage.membergroup;

import com.jshoperxms.Response;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.IBaseCtrl;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.mall.backstage.vo.member.MemberGroupAttrVo;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.json.GsonJson;
import com.jshoperxms.controller.utils.statickey.SerialKeys;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.MemberGroupT;
import com.jshoperxms.service.MemberGroupTService;
import com.jshoperxms.service.impl.Serial;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by sdywcd on 16/10/20.
 * Des:
 */
@Controller
@RequestMapping("/mall/membergroup")
public class MemberGroupTController extends BaseTController implements IBaseCtrl<MemberGroupT>{

    @Resource
    private MemberGroupTService memberGroupTService;

    private Map<String, Object> responsedata = new HashMap<>();

    @RequestMapping(value="/save",method= RequestMethod.POST)
    @Override
    public ResponseEntity save(@RequestBody MemberGroupT rq) {
        if(StringUtils.isNotBlank(rq.getName())){
            if(checkDuplicates(rq.getName())){
                MemberGroupT bean=new MemberGroupT();
                bean.setId(this.serial.Serialid(SerialKeys.MEMBERGROUP));
                bean.setAttrs(rq.getAttrs());
                bean.setName(rq.getName());
                bean.setStatus(rq.getStatus());
                bean.setStoreid(StaticKey.EMPTY);
                bean.setCreatetime(DateTools.getSystemTimeBi());
                bean.setUpdatetime(DateTools.getSystemTimeBi());
                bean.setCreatorid(BaseTools.getAdminCreateId());
                bean.setVersiont(1);
                this.memberGroupTService.save(bean);
                responsedata.put(TagWords.SUCCESS, true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }else{
                responsedata.put(TagWords.SUCCESS,false);
                responsedata.put(TagWords.MSG, WarnWrods.ERROR_HAVE_KEY);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }


    @RequestMapping(value="/find",method= RequestMethod.POST)
    @Override
    public ResponseEntity find(@RequestBody MemberGroupT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            MemberGroupT bean=this.memberGroupTService.findByPK(MemberGroupT.class,rq.getId());
            if(bean!=null){
                responsedata.put(TagWords.BEAN,bean);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }
        }
        return Response.success(responsedata);
    }

    @RequestMapping(value="/del",method= RequestMethod.POST)
    @Override
    public ResponseEntity del(@RequestBody MemberGroupT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            String ids[]=StringUtils.split(rq.getId(),TagWords.SPLITDOT);
            for(String s:ids){
                MemberGroupT bean=this.memberGroupTService.findByPK(MemberGroupT.class,s);
                if(bean!=null){
                    bean.setStatus(BaseEnums.DataUsingState.DEL.getState());
                    bean.setUpdatetime(DateTools.getSystemTimeBi());
                    this.memberGroupTService.update(bean);
                }
            }
            responsedata.put(TagWords.SUCCESS,true);
            responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        }
        return Response.success(responsedata);
    }

    @RequestMapping(value="/update",method= RequestMethod.POST)
    @Override
    public ResponseEntity update(@RequestBody MemberGroupT rq) {
        if(StringUtils.isBlank(rq.getId())){
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }else{
            if(checkDuplicates(rq.getName())){
                MemberGroupT bean=this.memberGroupTService.findByPK(MemberGroupT.class,rq.getId());
                bean.setAttrs(rq.getAttrs());
                bean.setName(rq.getName());
                bean.setStatus(rq.getStatus());
                bean.setUpdatetime(DateTools.getSystemTimeBi());
                bean.setVersiont(bean.getVersiont()+1);
                this.memberGroupTService.update(bean);
                responsedata.put(TagWords.SUCCESS,true);
                responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
            }else{
                responsedata.put(TagWords.SUCCESS,false);
                responsedata.put(TagWords.MSG,WarnWrods.ERROR_HAVE_KEY);
            }
        }
        return Response.success(responsedata);
    }

    @RequestMapping(value="/findAll",method= RequestMethod.POST)
    @Override
    public ResponseEntity findAll() {
        Criterion criterion=Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState());
        List<MemberGroupT>list=this.memberGroupTService.findByCriteria(MemberGroupT.class, criterion, Order.desc(TagWords.UPDATETIME));
        responsedata.put(TagWords.BEANLIST,list);
        responsedata.put(TagWords.SUCCESS, true);
        responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
        return Response.success(responsedata);
    }

    @RequestMapping(value="/findByPage",method= RequestMethod.POST)
    @Override
    public ResponseEntity findByPage(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
        findCustomSearch(searchModel,search,ordervalue,ordertype);
        return Response.success(responsedata);
    }

    @Override
    public void findCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {
        if(searchModel.getIsCustomSearch()==1){
            int currentPage=searchModel.getCalCurrentPage();
            int lineSize = searchModel.getLength();
            Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
            if(StringUtils.isNotBlank(searchModel.getName())){
                criterion=Restrictions.and(criterion).add(Restrictions.like("name",searchModel.getName(), MatchMode.ANYWHERE));
            }
            if(StringUtils.isNotBlank(search)){
                criterion=Restrictions.and(criterion).add(Restrictions.like("name",search,MatchMode.ANYWHERE));
            }
            int records=this.memberGroupTService.count(MemberGroupT.class,criterion).intValue();
            searchModel.setRecordsTotal(records);
            searchModel.setRecordsFiltered(records);
            responsedata.put(TagWords.RECORDSTOTAL,records);
            responsedata.put(TagWords.RECORDSFILTERED,records);
            List<MemberGroupT> list = this.memberGroupTService.findByCriteriaByPage(
                    MemberGroupT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
                    lineSize);
            this.processPageList(list);
        }else{
            if(StringUtils.isNotBlank(search)){
                filterSearch(searchModel,search);
            }else{
                findDefaultAll(searchModel,ordervalue,ordertype);
            }
        }
    }

    @Override
    public void filterSearch(SearchModel searchModel, String search) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        criterion=Restrictions.and(criterion).add(Restrictions.like("name",search,MatchMode.ANYWHERE));
        int records=this.memberGroupTService.count(MemberGroupT.class,criterion).intValue();
        searchModel.setRecordsTotal(records);
        searchModel.setRecordsFiltered(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        List<MemberGroupT> list = this.memberGroupTService.findByCriteriaByPage(
                MemberGroupT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
                lineSize);
        this.processPageList(list);
    }

    @Override
    public void findDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {
        int currentPage=searchModel.getCalCurrentPage();
        int lineSize = searchModel.getLength();
        Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
        int records=this.memberGroupTService.count(MemberGroupT.class,criterion).intValue();
        searchModel.setRecordsFiltered(records);
        searchModel.setRecordsTotal(records);
        responsedata.put(TagWords.RECORDSTOTAL,records);
        responsedata.put(TagWords.RECORDSFILTERED,records);
        Order order=BaseTools.orderByParam("name",ordervalue,ordertype);
        List<MemberGroupT> list = this.memberGroupTService.findByCriteriaByPage(
                MemberGroupT.class, criterion,order, currentPage,
                lineSize);
        this.processPageList(list);
    }

    @Override
    public void processPageList(List<MemberGroupT> list) {
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        for (Iterator<MemberGroupT> it = list.iterator(); it.hasNext(); ) {
            MemberGroupT bean = it.next();
            Map<String, Object> cellMap = new HashMap<String, Object>();
            cellMap.put("id", bean.getId());
            cellMap.put("name", bean.getName());
            List<String>gst=new ArrayList<>();
            if(StringUtils.isNotBlank(bean.getAttrs())){
                List<MemberGroupAttrVo>mlist= GsonJson.parseJsonToData(bean.getAttrs(),MemberGroupAttrVo.class);
                if(!mlist.isEmpty()){
                    for(MemberGroupAttrVo g:mlist){
                        gst.add(g.getAttrname());
                    }
                }
            }
            cellMap.put("attrs",StringUtils.join(gst.toArray(),TagWords.SPLITDOT));
            cellMap.put("status", BaseEnums.DataUsingState.getName(bean.getStatus()));
            cellMap.put("updatetime", DateTools.formateLongDateToString(bean.getUpdatetime().longValue()));
            cellMap.put("version", bean.getVersiont());
            data.add(cellMap);
        }
        responsedata.put(TagWords.DATA, data);
    }

    @Override
    public boolean checkDuplicates(String str) {
        if(StringUtils.isBlank(str)){
            return false;
        }
        Criterion criterion= Restrictions.eq("name",str);
        MemberGroupT bean=this.memberGroupTService.findOneByCriteria(MemberGroupT.class, criterion);
        if(bean!=null){
            return false;
        }
        return true;
    }
}
